<template>
  <div>
    <h3>拖拽排序列表</h3>
    <draggable v-model="list" @end="updateOrder">
      <transition-group>
        <div class="item" v-for="(item, index) in list" :key="item.id" :style="{ backgroundColor: item.color }">
          {{ item.name }}
        </div>
      </transition-group>
    </draggable>
    <h4>当前顺序：</h4>
    <pre>{{ JSON.stringify(order, null, 2) }}</pre>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  components: {
    draggable
  },
  data() {
    return {
      list: [
        { id: 1, name: "项目1", color: this.getRandomColor() },
        { id: 2, name: "项目2", color: this.getRandomColor() },
        { id: 3, name: "项目3", color: this.getRandomColor() },
        { id: 4, name: "项目4", color: this.getRandomColor() },
        { id: 5, name: "项目5", color: this.getRandomColor() }
      ],
      order: [] // 用于存储当前顺序
    };
  },
  methods: {
    updateOrder(event) {
      // 更新 order 数据
      this.order = this.list.map((item) => item.id);

      // 打印当前顺序
      console.log("当前顺序：", this.order);
    },
    getRandomColor() {
      // 生成随机颜色
      const letters = "0123456789ABCDEF";
      let color = "#";
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }
  }
};
</script>

<style scoped>
.item {
  padding: 10px;
  margin: 5px 0;
  border: 1px solid #ccc;
  color: white;
  /* 设置文字颜色为白色，以便在深色背景上显示 */
  cursor: move;
}
</style>